<template>
  <div class="widget-form-container" ref="content">
    <div v-if="!widgetForm.list" class="form-empty">从左侧拖拽来添加字段</div>
    <a-form>
      <grid-layout
        class="widget-form-list droppable-element"
        ref="gridlayout"
        v-model:layout="widgetForm.list"
        :col-num="4"
        :row-height="30"
        :is-draggable="widgetFormRef == 'preview' ? false : true"
        :is-resizable="widgetFormRef == 'preview' ? false : true"
        :is-mirrored="false"
        :vertical-compact="true" 
        :margin="[10, 10]"
        :use-css-transforms="true"
      >
        <grid-item
          class="grid-item"
          ref="gridItem"
          v-for="element in widgetForm.list"
          :x="element.x"
          :y="element.y"
          :w="element.w"
          :h="element.h"
          :i="widgetFormRef == 'preview' ? '' : element.i"
          :key="element.key"
          @click.stop="handleItemClick(element)"
        >
          <AntdWidgetFormItem
            v-if="element.key"
            :element="element"
            :selectWidget="widgetFormSelect"
            :widgetFormRef="widgetFormRef"
            @delete="handleDeleteClick(element)"
          />
        </grid-item> 
      </grid-layout>
    </a-form>
  </div>
</template>

<script lang="ts">
  import { defineComponent, PropType, reactive  } from 'vue';
  import AntdWidgetFormItem from './AntdWidgetFormItem.vue';
  import SvgIcon from '../components/SvgIcon.vue';
  import { WidgetForm } from '../config/antd';

  export default defineComponent({
    name: 'AntdWidgetForm',
    components: { SvgIcon, AntdWidgetFormItem },
    props: {
      widgetForm: {
        type: Object as PropType<WidgetForm>,
        required: true,
      },
      widgetFormSelect: {
        type: Object,
      },
      widgetFormRef: {
        type: String,
      },
    },

    emits: ['update:widgetForm', 'update:widgetFormSelect'],
    setup(props, context) {
      let FormSelect = reactive({});

      const handleItemClick = (row: any) => {
        FormSelect = row;
        console.log(FormSelect);
        context.emit('update:widgetFormSelect', row);
      };


      const handleDeleteClick = (item) => {
        let oldList = JSON.parse(JSON.stringify(props.widgetForm.list));

        for (let i = 0; i < oldList.length; i++) {
          if (oldList[i].key == item.key) {
            oldList.splice(i, 1);
          }
        }
        context.emit('update:widgetFormSelect', item)
        context.emit('update:widgetForm',{ ...props.widgetForm, list: oldList });
      };

      return {
        FormSelect,
        handleItemClick,
        handleDeleteClick,
      };
    },
  });
</script>
